package com.orangeandbronze.demos.mapreduce;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class UploadHandler extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		if (id != null && ((id = id.trim()).length()) > 0) {
			BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
			blobstoreService.serve(new BlobKey(id), response);
		} else {
			// TODO Redirect to home page?
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// Handle uploaded files
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		Map<String, List<BlobKey>> uploads = blobstoreService.getUploads(request);
		List<BlobKey> blobKeys = uploads.get("file");
		// blobstoreService.getBlobInfos(request);

		// Store the BlobKey in our datastore for later retrieval
		DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
		UserService userService = UserServiceFactory.getUserService();
		final User user = userService.getCurrentUser();
		final Date now = now();
		final BlobKey blobkey = blobKeys.get(0);
		Entity entity = new Entity(
				FileMetadata.KIND, FileMetadata.getKeyName(user, now, blobkey),
				KeyFactory.createKey("user", user.getUserId()));
		entity.setProperty("owner", user);
		entity.setProperty("filename", request.getParameter("name"));
		entity.setProperty("uploadedOn", now);
		// entity.setProperty("source", "uploaded by user");
		entity.setProperty("blobkey", blobkey.getKeyString());
		datastoreService.put(entity);
		response.sendRedirect("/demo");
	}

	protected Date now() {
		return new java.util.Date();
	}

}
